
import 'package:flutter/material.dart';


class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  final String title;
  final bool alwaysShowBack;

  const CustomAppBar({
    super.key,
    required this.title,
    this.alwaysShowBack = false,
  });

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text(title, style: const TextStyle(fontWeight: FontWeight.bold),textAlign:TextAlign.center),
      leading: _buildBackButton(context),
      actions: [
        IconButton(
          icon: const Icon(Icons.refresh),
          onPressed: () {
            // 模拟刷新操作
            // ScaffoldMessenger.of(context).showSnackBar(
            //   SnackBar(
            //     content: const Text('页面已刷新'),
            //     backgroundColor: Colors.deepPurple[700],
            //     behavior: SnackBarBehavior.floating,
            //   ),
            // );

          },
        ),
      ],
    );
  }

  Widget? _buildBackButton(BuildContext context) {
    // 始终显示返回按钮
    return IconButton(
      // icon: const Icon(Icons.arrow_back), <
      // u_turn_left_rounded  掉头
      // icon: Icon(Icons.arrow_back_ios, color: Colors.black),
       icon: Transform.rotate(
      angle: 1.5708, // 90度对应的弧度值 (π/2)
      child: Icon(Icons.arrow_back, color: Colors.black),
    )
       ,
       
      tooltip: '返回',
      onPressed: () => _handleBackAction(context),
    );
  }

  void _handleBackAction(BuildContext context) {
    if (Navigator.canPop(context)) {
      // 如果路由栈可弹出，则执行弹出操作
      Navigator.maybePop(context);
    } else {
      // 如果已在首页，则导航到默认视图
      Navigator.pushNamedAndRemoveUntil(
        context,
        '/',
        (route) => false,
      );
      
      // 显示提示信息
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('已返回应用首页'),
          duration: Duration(seconds: 1),
        ),
      );
    }
  }
}